package top.yvyan.guettable.moreFun;

import android.annotation.SuppressLint;
import android.view.View;
import android.widget.ExpandableListView;

import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.ContextCompat;

import java.util.HashMap;
import java.util.Map;

import top.yvyan.guettable.Gson.ExamScoreNew;
import top.yvyan.guettable.Gson.ProgramModel;
import top.yvyan.guettable.Gson.Semester;
import top.yvyan.guettable.R;
import top.yvyan.guettable.adapter.GradesAdapter;
import top.yvyan.guettable.bean.GradesBean;
import top.yvyan.guettable.data.MoreData;
import top.yvyan.guettable.data.TokenData;
import top.yvyan.guettable.service.fetch.StaticService;
import top.yvyan.guettable.util.AppUtil;
import top.yvyan.guettable.util.BackgroundUtil;
import top.yvyan.guettable.util.ToastUtil;

public class GradesActivity extends BaseFuncActivity {

    public GradesBean gradesBean;

    @Override
    protected void childInit() {
        setTitle(getResources().getString(R.string.moreFun_credits));
        setShowMore(true);
        AppUtil.reportFunc(getApplicationContext(), getString(R.string.moreFun_credits));

    }

    @Override
    protected void showContent() {
        baseSetContentView(R.layout.activity_grades);
        if (gradesBean == null) {
            gradesBean = MoreData.getGradesBean();
        }
        if (gradesBean != null) {
            try {
                gradesBean.initStruct();
                gradesBean.calcGrades();
                ExpandableListView expandableListView = findViewById(R.id.grades_list);
                GradesAdapter gradesAdapter = new GradesAdapter(this, expandableListView, gradesBean);
                expandableListView.setAdapter(gradesAdapter);
            } catch (Exception e) {
                ToastUtil.showToast(this, "加载缓存数据出现错误");
                MoreData.setGradesBean(null);
                gradesBean = null;
                e.printStackTrace();
            }
        }
        if (BackgroundUtil.isSetBackground(this)) {
            View v = findViewById(R.id.grades_tips);
            v.setBackgroundColor(ContextCompat.getColor(this, R.color.writeTransparent));
        } else {
            View v = findViewById(R.id.grades_tips);
            v.setBackgroundColor(ContextCompat.getColor(this, R.color.transparent));
        }
    }

    private ExamScoreNew scoreData;
    private ProgramModel programModel;
    Map<String, Semester> semesterMap = new HashMap<>();

    private GradesBean.UserOverride userOverride;

    @SuppressLint("NonConstantResourceId")
    @Override
    protected void showPopMenu(View v) {
        super.showPopMenu(v);
        PopupMenu popup = new PopupMenu(this, v);
        popup.getMenuInflater().inflate(R.menu.grade_popmenu, popup.getMenu());
        popup.setOnMenuItemClickListener(item -> {
            switch (item.getItemId()) {
                case R.id.clear_cache:
                    if (gradesBean != null) {
                        userOverride = gradesBean.userOverride;
                    }
                    gradesBean = null;
                    semesterMap = new HashMap<>();
                    MoreData.setGradesBean(gradesBean);
                    moreFunService.update();
                    break;
                case R.id.clear_user_override:
                    userOverride = null;
                    gradesBean.userOverride=new GradesBean.UserOverride();
                    semesterMap = new HashMap<>();
                    MoreData.setGradesBean(gradesBean);
                    showContent();
                    break;
                default:
                    break;
            }
            return true;
        });
        popup.show();
    }

    @Override
    public int updateData(TokenData tokenData) {
        if (gradesBean != null) {
            if (gradesBean.semesterMap != null) {
                semesterMap = gradesBean.semesterMap;
            }
            if (gradesBean.userOverride != null) {
                userOverride = gradesBean.userOverride;
            }
        }
        boolean state = tokenData.tryUpdate(() -> {
            this.updateProgress("正在登录");
        }, () -> {
            this.updateProgress("获取成绩单");
            scoreData = StaticService.getExamScoreNew(this, tokenData.getbkjwTestCookie());
            return scoreData != null;
        }, () -> {
            this.updateProgress("查询并解析学期代码");
            for (String semesterId : scoreData.semesterId2studentGrades.keySet()) {
                if (semesterMap.containsKey(semesterId)) continue;
                this.updateProgress("查询并解析学期代码-" + semesterId);
                Semester semesterInfo = StaticService.querySemester(this, semesterId, tokenData.getbkjwTestCookie());
                if (semesterInfo == null) {
                    return false;
                }
                semesterMap.put(semesterId, semesterInfo);
            }
            return true;
        }, () -> {
            this.updateProgress("查询培养方案");
            try {
                programModel = StaticService.getProgramModel(this, tokenData.getbkjwTestCookie());
            } catch (Exception ignore) {

            }
            return programModel != null;
        });
        gradesBean = new GradesBean(scoreData, programModel, semesterMap, userOverride);
        MoreData.setGradesBean(gradesBean);
        if (state) {
            return 5;
        }
        return 1;
    }
}
